import random

from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import mixins
from rest_framework.filters import OrderingFilter
from rest_framework.generics import CreateAPIView, RetrieveAPIView, GenericAPIView, ListAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from ansewr.models import Respond, Question
from headline.models import News
from .serializers import SMSCodeSerializer, CreateUserSerializer, PersonTitleSerializer, PersonDetailSerializer, \
    UserBrowsingHistorySerializer, NewsSerializer, MyAnswerSerializer, MyQuestionSerializer
from .models import User

from . import constants
from celery_tasks.sms.tasks import send_sms_code


# url('^users/$')
class UserView(CreateAPIView):
    """
    用户注册
    传入参数：
        username, password, sms_code, mobile, allow
    """
    serializer_class = CreateUserSerializer


# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    """
    用户名数量
    """
    def get(self, request, username):
        """
        获取指定用户名数量
        """
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
class MobileCountView(APIView):
    """
    手机号数量
    """
    def get(self, request, mobile):
        """
        获取指定手机号数量
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count,
        }

        return Response(data)


# url('^sms_codes/(?P<mobile>1[3-9]\d{9})/$', views.SMSCodeView.as_view()),
class SMSCodeView(GenericAPIView):
    """
    短信验证码
    传入参数：
        mobile
    """
    serializer_class = SMSCodeSerializer

    def get(self, request, mobile):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print("短信验证码：%s"%sms_code)

        # 保存短信验证码  保存发送记录
        redis_conn = get_redis_connection('verify_codes')

        # redis管道
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 让管道通知redis执行命令
        pl.execute()
        # 使用celery发送短信验证码
        expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        send_sms_code.delay(mobile, [sms_code, expires], constants.SMS_CODE_TEMP_ID)

        return Response({'message': 'OK'})


class UserAuthorizeView(ObtainJSONWebToken):
    """用户登录认证视图"""
    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)

        return response


class PersonAccount(RetrieveAPIView, UpdateAPIView):
    """个人设置"""
    # queryset = User.objects.all()
    serializer_class = PersonTitleSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user



class PersonTitleView(RetrieveAPIView):
    """
    个人页面头部显示
    """

    # queryset = User.objects.all()
    serializer_class = PersonTitleSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user




class PersonDetailView(RetrieveAPIView, UpdateAPIView):
    """
    个人详情
    """
    # queryset = User.objects.all()
    serializer_class = PersonDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class UserBrowsingHistoryView(CreateAPIView):
    """
    用户浏览历史记录
    """
    serializer_class = UserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]


    def get(self, request):
        # user_id
        user_id = request.user.id

        # 查询redis  list
        redis_conn = get_redis_connection('history')
        news_id_list = redis_conn.lrange('history_%s' % user_id, 0, 4)

        # 数据库
        # sku_object_list = SKU.objects.filter(id__in=sku_id_list)

        news_list = []
        for history_news_id in news_id_list:
            news = News.objects.get(id=history_news_id)
            news_list.append(news)

        # 序列化 返回
        serializer = NewsSerializer(news_list, many=True)
        return Response(serializer.data)


class MyAnswerView(ListAPIView):
    # queryset = Respond.objects.all().order_by('create_time')[1:5]
    serializer_class = MyAnswerSerializer
    permission_classes = [IsAuthenticated]


class MyQuestionsView(ListAPIView):
    # queryset = Question.objects.all().order_by('create_time')[1:5]
    queryset = Question.objects.all()
    serializer_class = MyQuestionSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = None





